package huzh.foundation.appserver;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.transaction.UserTransaction;

/**
 *<p>title:JBossUtil</p>
 *<p>description:</p>
 * @since 2014-6-8
 * @author huzh
 * @version 1.0
 */
public class JBossUtil extends AbstractAppServerService {

    /**JBOSS*/
    public static final String JBOSS = "jboss";
    /**JBOSS_JNDI_FACTORY*/
    public static final String JBOSS_JNDI_FACTORY = "org.jnp.interfaces.NamingContextFactory";
    /**JBOSS_JNDI_URL_PKG_PREFIXES*/
    public static final String JBOSS_JNDI_URL_PKG_PREFIXES = "org.jboss.naming:org.jnp.interfaces";
    /**JBOSS_TX*/
    public static final String JBOSS_TX = "UserTransaction";
    /**initialContext*/
    private static InitialContext initialContext = null;

    /**
     * @return
     * @throws NamingException
     */
    public InitialContext getInitialContext() throws NamingException {
        if (initialContext != null) {
            return initialContext;
        }
        Hashtable<String,String> env = new Hashtable<String,String>();
        env.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
        env.put("java.naming.provider.url", url);
        env.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
        initialContext = new InitialContext(env);
        return initialContext;
    }

    /**
     * @param dsJNDIName
     * @return
     * @throws NamingException
     */
    public DataSource getDataSource(String dsJNDIName) throws NamingException {
        Context ctx = getEnvContext();
        return getDataSource(ctx, dsJNDIName);
    }

    /**
     * @return
     * @throws NamingException
     */
    public UserTransaction getUserTx() throws NamingException {
        Context ctx = getInitialContext();

        UserTransaction tx = getUserTx(ctx, "UserTransaction");
        return tx;
    }

    /**
     * @return
     * @throws NamingException
     */
    public Context getEnvContext() throws NamingException {
        Context ctx = getInitialContext();
        return getEnvContext(ctx);
    }

}
